package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Assignment
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import coil.compose.AsyncImage
import com.sinogrand.elevator.data.models.UserInfo
import com.sinogrand.elevator.data.models.ProfileInfo
import com.sinogrand.elevator.data.models.DeptInfo
import com.sinogrand.elevator.network.NetworkClient
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.TokenManager
import com.google.gson.JsonObject
import kotlinx.coroutines.launch
import android.util.Log

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileScreen(
    onNavigateToSettings: () -> Unit = {},
    onNavigateToMyApproval: () -> Unit = {},
    onNavigateToMyWorkOrder: () -> Unit = {}
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    
    // 状态管理
    var profileInfo by remember { mutableStateOf<ProfileInfo?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    
    // API服务和Token管理器
    val apiService = remember { NetworkClient.getApiService(context) }
    val tokenManager = remember { TokenManager(context) }
    
    // 加载个人信息（支持缓存）
    suspend fun loadProfileInfo() {
        try {
            Log.d(LogTags.MAIN_ACTIVITY, "开始加载个人信息")
            
            // 先尝试从缓存加载
            val cachedUserInfo = tokenManager.getUserInfo()
            if (cachedUserInfo != null) {
                Log.d(LogTags.MAIN_ACTIVITY, "📱 从缓存加载用户信息: ${cachedUserInfo.real_name}")
                // 将UserInfo转换为ProfileInfo
                profileInfo = ProfileInfo(
                    id = cachedUserInfo.id,
                    mobile = cachedUserInfo.mobile,
                    openid = cachedUserInfo.openid,
                    avatar = cachedUserInfo.avatar,
                    real_name = cachedUserInfo.real_name,
                    id_card_no = cachedUserInfo.id_card_no,
                    signature = cachedUserInfo.signature,
                    role_info = cachedUserInfo.role_info,
                    dept_info = cachedUserInfo.dept_info,
                    has_valid_project = cachedUserInfo.has_valid_project,
                    template_list = cachedUserInfo.template_list
                )
                isLoading = false
                errorMessage = null
            }
            
            // 无论是否有缓存，都尝试从API获取最新数据
            isLoading = true
            errorMessage = null
            
            val request = JsonObject() // 空的请求体
            val apiResponse = apiService.getProfileInfo(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                profileInfo = apiResponse.data.info
                
                // 将ProfileInfo转换为UserInfo并保存到缓存
                val userInfo = UserInfo(
                    id = apiResponse.data.info.id,
                    mobile = apiResponse.data.info.mobile,
                    openid = apiResponse.data.info.openid,
                    avatar = apiResponse.data.info.avatar,
                    real_name = apiResponse.data.info.real_name,
                    id_card_no = apiResponse.data.info.id_card_no,
                    signature = apiResponse.data.info.signature,
                    role_info = apiResponse.data.info.role_info,
                    dept_info = apiResponse.data.info.dept_info ?: com.sinogrand.elevator.data.models.DeptInfo(0, ""),
                    has_valid_project = apiResponse.data.info.has_valid_project,
                    template_list = apiResponse.data.info.template_list
                )
                tokenManager.saveUserInfo(userInfo)
                
                Log.i(LogTags.MAIN_ACTIVITY, "✅ 成功加载并缓存个人信息: ${profileInfo?.real_name}")
            } else {
                Log.e(LogTags.MAIN_ACTIVITY, "❌ 加载个人信息失败: ${apiResponse.msg}")
                errorMessage = apiResponse.msg
            }
        } catch (e: Exception) {
            Log.e(LogTags.MAIN_ACTIVITY, "💥 加载个人信息异常: ${e.message}", e)
            errorMessage = "加载失败: ${e.message}"
        } finally {
            isLoading = false
        }
    }
    
    // 初始加载
    LaunchedEffect(Unit) {
        loadProfileInfo()
    }
    
    // 使用 rememberSaveable 保持滚动状态
    val scrollState = rememberSaveable(saver = androidx.compose.foundation.ScrollState.Saver) {
        androidx.compose.foundation.ScrollState(0)
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(scrollState)
            .background(
                Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFFF8FAFC),
                        Color(0xFFF1F5F9)
                    )
                )
            )
    ) {
        // 顶部导航栏
        TopAppBar(
            title = {
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "个人中心",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = Color.White,
                titleContentColor = Color(0xFF1F2937)
            ),
            modifier = Modifier.shadow(2.dp)
        )
        
        // 个人信息卡片
        UserProfileCard(
            profileInfo = profileInfo,
            isLoading = isLoading,
            errorMessage = errorMessage,
            onRetry = {
                scope.launch {
                    loadProfileInfo()
                }
            }
        )
        
        // 功能列表
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp)
        ) {
            // 我的审批
            ProfileMenuItem(
                icon = Icons.AutoMirrored.Filled.Assignment,
                title = "我的审批",
                onClick = onNavigateToMyApproval
            )
            
            // 我的工单
            ProfileMenuItem(
                icon = Icons.Default.Work,
                title = "我的工单",
                onClick = onNavigateToMyWorkOrder
            )
            
            // 设置
            ProfileMenuItem(
                icon = Icons.Default.Settings,
                title = "设置",
                onClick = onNavigateToSettings
            )
        }
    }
}

@Composable
fun ProfileMenuItem(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
    isDestructive: Boolean = false,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = if (isDestructive) Color(0xFFDC2626) else Color(0xFF6B7280),
                modifier = Modifier.size(24.dp)
            )
            
            Spacer(modifier = Modifier.width(16.dp))
            
            Text(
                text = title,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                color = if (isDestructive) Color(0xFFDC2626) else Color(0xFF1F2937)
            )
            
            Spacer(modifier = Modifier.weight(1f))
            
            Icon(
                imageVector = Icons.AutoMirrored.Filled.ArrowForward,
                contentDescription = null,
                tint = Color(0xFF9CA3AF),
                modifier = Modifier.size(20.dp)
            )
        }
    }
}

@Composable
fun UserProfileCard(
    profileInfo: ProfileInfo?,
    isLoading: Boolean,
    errorMessage: String?,
    onRetry: () -> Unit
) {
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(16.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            when {
                isLoading -> {
                    // 加载状态
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .clip(CircleShape)
                            .background(Color(0xFFF3F4F6)),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(32.dp),
                            color = Color(0xFF3B82F6)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Text(
                        text = "加载中...",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF6B7280)
                    )
                }
                
                errorMessage != null -> {
                    // 错误状态
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .clip(CircleShape)
                            .background(Color(0xFFFEF2F2)),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = "错误",
                            tint = Color(0xFFDC2626),
                            modifier = Modifier.size(32.dp)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Text(
                        text = "加载失败",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFFDC2626)
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = errorMessage,
                        fontSize = 14.sp,
                        color = Color(0xFF6B7280),
                        textAlign = androidx.compose.ui.text.style.TextAlign.Center
                    )
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Button(
                        onClick = onRetry,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF3B82F6)
                        )
                    ) {
                        Text("重试")
                    }
                }
                
                profileInfo != null -> {
                    // 正常状态 - 显示用户信息
                    // 用户头像
                    if (!profileInfo.avatar.isNullOrEmpty()) {
                        AsyncImage(
                            model = profileInfo.avatar,
                            contentDescription = "用户头像",
                            modifier = Modifier
                                .size(80.dp)
                                .clip(CircleShape),
                            contentScale = ContentScale.Crop
                        )
                    } else {
                        // 默认头像
                        Box(
                            modifier = Modifier
                                .size(80.dp)
                                .clip(CircleShape)
                                .background(Color(0xFF3B82F6)),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = profileInfo.real_name?.take(1)?.uppercase() ?: "用",
                                color = Color.White,
                                fontSize = 32.sp,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    // 用户姓名
                    Text(
                        text = profileInfo.real_name ?: "未知用户",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    // 手机号
                    Text(
                        text = profileInfo.mobile.toString(),
                        fontSize = 16.sp,
                        color = Color(0xFF6B7280)
                    )
                    
                    Spacer(modifier = Modifier.height(12.dp))
                    
                    // 角色信息
                    InfoChip(
                        icon = Icons.Default.Person,
                        text = profileInfo.role_info.name
                    )
                }
                
                else -> {
                    // 空状态
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .clip(CircleShape)
                            .background(Color(0xFFF3F4F6)),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Default.Person,
                            contentDescription = "用户",
                            tint = Color(0xFF9CA3AF),
                            modifier = Modifier.size(32.dp)
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Text(
                        text = "暂无信息",
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF6B7280)
                    )
                }
            }
        }
    }
}

@Composable
fun InfoChip(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    text: String
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = Color(0xFF6B7280),
            modifier = Modifier.size(16.dp)
        )
        
        Text(
            text = text,
            fontSize = 14.sp,
            color = Color(0xFF6B7280),
            fontWeight = FontWeight.Medium
        )
    }
}
